package com.xchat.stevenzack.spycamera;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by steven on 17-6-10.
 */

public class MainActivity extends AppCompatActivity {
    private Camera mCamera0,mCamera1;
    private CameraPreview0 mPreview0;
    private CameraPreview1 mPreview1;
    private Point point;
    private boolean mCameraToggle=false;
    private static String TAG="== MainActivity ===";
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.arg1){
                case 0:
                    initUI1();
                    if (mCamera1!=null){
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try{
                                    Thread.sleep(1000);
                                    mCamera1.takePicture(null,null,mPicture1);
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }else {
                        Toast.makeText(MainActivity.this, "Front camera open failed,mCameraToggle = "+String.valueOf(mCameraToggle), Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        point=new Point();
        getWindowManager().getDefaultDisplay().getSize(point);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},CONTEXT_INCLUDE_CODE);
            ((FrameLayout)findViewById(R.id.frame0)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initUI0();
                    initUI1();
                }
            });
        }else {
            initUI0();
            initUI1();
        }
        ((ImageButton)findViewById(R.id.switcher)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCamera1!=null){
                    mCamera1.release();
                    mCamera1=null;
                }
                if (mCamera0!=null){
                    mCamera0.release();
                    mCamera0=null;
                }
                ((FrameLayout)findViewById(R.id.frame0)).removeAllViews();
                ((FrameLayout)findViewById(R.id.frame1)).removeAllViews();
                mCameraToggle=!mCameraToggle;
                initUI0();
                initUI1();
            }
        });
        ((ImageButton) findViewById(R.id.shutter)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCamera0!=null&&mCamera1==null){
                    mCamera0.takePicture(null,null,mPicture0);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try{
                                Thread.sleep(1000);
                                mCamera0.release();
                                mCamera0=null;
                                Message msg=new Message();
                                msg.arg1=0;
                                handler.sendMessage(msg);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }else if (mCamera0!=null&&mCamera1!=null){
                    mCamera0.takePicture(null,null,mPicture0);
                    mCamera1.takePicture(null,null,mPicture1);
                }else if (mCamera0==null&&mCamera1!=null){
                    mCamera0.takePicture(null,null,mPicture0);
                    mCamera1.takePicture(null,null,mPicture1);
                }
            }
        });
    }
    @Override
    protected void onPause() {
        super.onPause();
        if (mCamera1!=null){
            mCamera1.release();
            mCamera1=null;
        }
        if (mCamera0!=null){
            mCamera0.release();
            mCamera0=null;
        }
        ((FrameLayout)findViewById(R.id.frame0)).removeAllViews();
        ((FrameLayout)findViewById(R.id.frame1)).removeAllViews();
    }

    @Override
    protected void onResume() {
        super.onResume();
        this.findViewById(Window.ID_ANDROID_CONTENT).setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},CONTEXT_INCLUDE_CODE);
            ((FrameLayout)findViewById(R.id.frame0)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    initUI0();
                    initUI1();
                }
            });
        }else {
            initUI0();
            initUI1();
        }
        refreshImgView();
    }

    private void initUI0(){
        if (checkCameraHardware(this)) {
            try {
                if (mCameraToggle)
                    mCamera0=openFrontFacingCameraGingerbread();
                else
                    mCamera0 = Camera.open();

            } catch (Exception e) {
                Toast.makeText(this, "e=" + e.toString()+"  mCameraToggle="+String.valueOf(mCameraToggle), Toast.LENGTH_SHORT).show();
            }
            if (mCamera0 != null) {
                mCamera0.setDisplayOrientation(90);
                Camera.Parameters parameters0 = mCamera0.getParameters();
                parameters0.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                parameters0.setPreviewSize(point.y,point.x);
                parameters0.setPictureSize(point.y,point.x);
                if (mCameraToggle) {
                    parameters0.setRotation(270);
                } else
                    parameters0.setRotation(90);
                mCamera0.setParameters(parameters0);
                mPreview0 = new CameraPreview0(this, mCamera0);
                FrameLayout preview = (FrameLayout) findViewById(R.id.frame0);
                preview.addView(mPreview0);
            }
        }
        ((FrameLayout)findViewById(R.id.frame0)).setOnClickListener(null);
    }
    private void initUI1(){
        try {
            if (!mCameraToggle){
                mCamera1=openFrontFacingCameraGingerbread();
            }else {
                mCamera1 = Camera.open();
            }
        } catch (Exception e) {
            Toast.makeText(this, "e=" + e.toString()+"  mCameraToggle="+String.valueOf(mCameraToggle), Toast.LENGTH_SHORT).show();
        }
        if ( mCamera1 != null) {
            mCamera1.setDisplayOrientation(90);
            Camera.Parameters parameters1 = mCamera1.getParameters();
            parameters1.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
            parameters1.setPreviewSize(point.y,point.x);
            parameters1.setPictureSize(point.y,point.x);
            if (!mCameraToggle)
                parameters1.setRotation(270);
            else
                parameters1.setRotation(90);
            mCamera1.setParameters(parameters1);
            mPreview1 = new CameraPreview1(MainActivity.this, mCamera1);
            FrameLayout preview1 = (FrameLayout) findViewById(R.id.frame1);
            preview1.addView(mPreview1);
        }
    }
    private Camera openFrontFacingCameraGingerbread() {
        int cameraCount = 0;
        Camera cam = null;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();
        for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
            Camera.getCameraInfo(camIdx, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                try {
                    cam = Camera.open(camIdx);
                } catch (RuntimeException e) {
                    Toast.makeText(this,"Camera failed to open: " + e.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
                }
            }
        }

        return cam;
    }
    private Camera.PictureCallback mPicture1 = new Camera.PictureCallback() {
        public String TAG="=== picture call back ===";
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES), "SpyCamera");
            if (!pictureFileDir.exists())pictureFileDir.mkdir();
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File file=new File(pictureFileDir.getAbsolutePath()+File.separator+timeStamp+".jpg");
            try {
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(data);
                fos.close();
            } catch (FileNotFoundException e) {
                Log.d(TAG, "File not found: " + e.getMessage());
            } catch (IOException e) {
                Log.d(TAG, "Error accessing file: " + e.getMessage());
            }
            File fileToOpen=new File(getSharedPreferences("settings", Context.MODE_PRIVATE).getString("lastImg",Environment.getExternalStorageDirectory().getAbsolutePath()));
            Intent i=new Intent(Intent.ACTION_VIEW, FileProvider.getUriForFile(MainActivity.this,MainActivity.this.getApplicationContext().getPackageName()+".provider",fileToOpen));
//            if (fileToOpen.isFile()) {
//                Intent i = new Intent(Intent.ACTION_VIEW, FileProvider.getUriForFile(MainActivity.this, MainActivity.this.getApplicationContext().getPackageName() + ".provider", fileToOpen));
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {
                startActivity(i);
            } catch (Exception e) {
                Intent i1 = new Intent(MainActivity.this, ShowImage.class);
                i1.putExtra("path", fileToOpen.getAbsolutePath());
                startActivity(i1);
            }
//            }
        }
    };
    private Camera.PictureCallback mPicture0 = new Camera.PictureCallback() {
        public String TAG="=== picture call back ===";
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFileDir = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES);
            if (!pictureFileDir.exists())pictureFileDir.mkdir();
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File file=new File(pictureFileDir.getAbsolutePath()+File.separator+timeStamp+".jpg");
            try {
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(data);
                fos.close();
            } catch (FileNotFoundException e) {
                Log.d(TAG, "File not found: " + e.getMessage());
            } catch (IOException e) {
                Log.d(TAG, "Error accessing file: " + e.getMessage());
            }
            getSharedPreferences("settings", Context.MODE_PRIVATE).edit().putString("lastImg", file.getAbsolutePath()).commit();
        }
    };
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }
    public static Bitmap rotateImage(Bitmap source, float angle) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
                matrix, true);
    }
    private void refreshImgView(){
        File file= new File(getSharedPreferences("settings", Context.MODE_PRIVATE).getString("lastImg",Environment.getExternalStorageDirectory().getAbsolutePath()));
        ImageView iv=(ImageView)findViewById(R.id.lastimg);
        if (file.exists()&&file.isFile()){
            iv.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            iv.setVisibility(View.VISIBLE);
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    File fileToOpen=new File(getSharedPreferences("settings", Context.MODE_PRIVATE).getString("lastImg",Environment.getExternalStorageDirectory().getAbsolutePath()));
                    Intent i=new Intent(Intent.ACTION_VIEW, FileProvider.getUriForFile(MainActivity.this,MainActivity.this.getApplicationContext().getPackageName()+".provider",fileToOpen));
                    i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    try {
                        startActivity(i);
                    } catch ( Exception e) {
                        Intent i1=new Intent(MainActivity.this,ShowImage.class);
                        i1.putExtra("path",fileToOpen.getAbsolutePath());
                        startActivity(i1);
                    }
                }
            });
        }else{
            iv.setVisibility(View.GONE);
        }

    }
}
